<template>
  <div class="common-upload">
    <el-upload
      action="#"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :show-file-list="showFileList"
      multiple
      name="filename"
      :http-request="httpRequestHandle"
      :file-list="fileListClone"
      :limit="limit"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>
<script>
import { getFileUrl } from '@/service/ship'

export default {
  name: 'PublicUpload',
  components: {},
  props: {
    fileList: {
      type: Array,
      default: () => {
        return []
      }
    },
    showFileList: {
      type: Boolean,
      default: true
    },
    limit: {
      type: Number,
      default: 10
    },
    largestSize: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      fileListClone: []
    }
  },
  watch: {
    fileList: {
      handler(val) {
        const arrList = val.map((ele) => {
          return Object.assign(ele, { name: ele.filename })
        })
        this.fileListClone = arrList
      },
      immediate: true
    }
  },
  methods: {
    // 自定义请求接口
    async httpRequestHandle(data) {
      data = data || {}
      const { file } = data
      const { name } = file
      const fd = new FormData()
      fd.append('file', file)
      this.$emit('setUploadLoding', true)
      const res = await getFileUrl(fd).finally(() => {
        this.$emit('setUploadLoding', false)
      })
      this.fileListClone.push({
        ...res,
        ossKey: res.mapKey,
        attachmentUrl: res.url,
        name,
        filename: name
      })
      this.getfileList()
    },
    // 删除
    handleRemove(file, fileArr) {
      this.fileListClone = fileArr
      this.getfileList()
    },
    // 设置
    getfileList() {
      this.$emit('setFileList', this.fileListClone)
    },
    beforeUpload(file) {
      const isLess = file.size / 1024 / 1024 <= this.largestSize
      if (!isLess) {
        this.$message({
          message: `文件不能超过${this.largestSize}M，请重新上传!`,
          type: 'error'
        })
        return false
      }
      return true
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
<style lang="scss">
.common-upload {
  .el-upload-list__item {
    transition: none ;
  }
}
</style>
